<template>
	<view class="print-setting-box">
		<!-- <lai-tab :tabList="tabList" :lineWidth="35" @onTabsClick="onTabsClick" :type="type"></lai-tab> -->
		<lai-notice text="*注：添加云打印机时，请确保云打印机已经开机并联网" :duration="5000"></lai-notice>
		<view class="set-print">
			<view class="top">
				<view class="name">打印机1</view>
				<view style="margin-left: 50rpx" class="print-pager" v-if="!id" @click="onBinding">绑定打印机</view>
				<view class="scan" v-if="!id" @click="onScanCode">
					<image src="../../../static/images/icon/扫码.png" style="width: 40rpx; height: 40rpx; vertical-align: bottom; margin-right: 10rpx"></image>
					扫码绑定
				</view>
				<view v-if="id" style="font-size: 24rpx; color: #6c6c6c; flex: 1; text-align: center">已添加</view>
				<view class="print-pager" v-if="id" @click="printTest">打印测试单</view>
				<view class="delete" v-if="id" @click="onDel"><u-icon name="trash" size="20"></u-icon></view>
			</view>
			<u--form labelPosition="left" label-width="90" :model="formData" :rules="rules" ref="uForm">
				<view class="content">
					<u-form-item label="打印机名称:" prop="name" borderBottom ref="item1">
						<u--input
							:customStyle="{
								backgroundColor: '#F3F4F6',
								padding: '5rpx 20rpx',
								color: '#999',
								border: 'none'
							}"
							v-model="formData.name"
							border="none"
						></u--input>
					</u-form-item>
					<u-form-item label="序列号(SN):" prop="sn" borderBottom ref="item1">
						<u--input
							:disabled="id"
							:customStyle="{
								backgroundColor: '#F3F4F6',
								padding: '5rpx 20rpx',
								color: '#999',
								border: 'none'
							}"
							border="surround"
							v-model="formData.sn"
						></u--input>
					</u-form-item>
					<u-form-item label="打印机Key:" prop="key" borderBottom ref="item1">
						<u--input
							:disabled="id"
							:customStyle="{
								backgroundColor: '#F3F4F6',
								padding: '5rpx 20rpx',
								color: '#999',
								border: 'none'
							}"
							v-model="formData.key"
							border="surround"
						></u--input>
					</u-form-item>
				</view>

				<!-- 打印小票类型start -->
				<view class="receipt-info" v-if="id">
					<u-cell-group>
						<u-cell arrow-direction="down">
							<template #title>
								<view style="display: flex; align-items: center">
									结账单
									<view class="placeholder"></view>
									<u-icon style="margin-left: 20rpx" name="eye" color="#687AAF" size="18" @click="openPopup('Receipt')"></u-icon>
									<text style="color: #687aaf; font-size: 24rpx" @click="openPopup('Receipt')">预览</text>
								</view>
							</template>
							<template #value>
								<view><u-switch @change="onSwitch('Receipt')" activeColor="#f3c45d" v-model="formData.isReceipt" size="20"></u-switch></view>
							</template>
						</u-cell>

						<u-cell arrow-direction="down" v-if="formData.isReceipt">
							<template #title>
								<view>
									<u-form-item :borderBottom="false" label-width="120" label="结账单打印份数:" prop="receiptCount">
										<u--input
											:customStyle="{
												backgroundColor: '#F3F4F6',
												color: '#999',
												border: 'none'
											}"
											v-model="formData.receiptCount"
											border="surround"
										></u--input>
									</u-form-item>
								</view>
							</template>
						</u-cell>

						<u-cell arrow-direction="down">
							<template #title>
								<view style="display: flex; align-items: center">
									厨打单
									<view class="placeholder"></view>
									<u-icon style="margin-left: 20rpx" name="eye" color="#687AAF" size="18" @click="openPopup('Kitchen')"></u-icon>
									<text style="color: #687aaf; font-size: 24rpx" @click="openPopup('Kitchen')">预览</text>
								</view>
							</template>
							<template #value>
								<view><u-switch @change="onSwitch('Kitchen')" activeColor="#f3c45d" v-model="formData.isKitchen" size="20"></u-switch></view>
							</template>
						</u-cell>

						<u-cell arrow-direction="down" v-if="formData.isKitchen">
							<template #title>
								<view>
									<u-form-item :borderBottom="false" label-width="120" label="厨打单打印份数" prop="kitchenCount">
										<u--input
											:customStyle="{
												backgroundColor: '#F3F4F6',

												color: '#999',
												border: 'none'
											}"
											v-model="formData.kitchenCount"
											border="surround"
										></u--input>
									</u-form-item>
								</view>
							</template>
						</u-cell>

						<u-cell arrow-direction="down" v-if="formData.isKitchen">
							<template #title>
								<view>
									<u-form-item :borderBottom="false" label-width="120" label="厨打单打印方式:" prop="foodPackPrintType">
										<u-radio-group style="margin-left: 10rpx" v-model="formData.foodPackPrintType">
											<u-radio
												activeColor="#f3c45d"
												:customStyle="{ marginTop: '6px', marginRight: '5px' }"
												v-for="(item, index) in foodPackPrintTypeList"
												:key="index"
												:label="item.name"
												:name="item.value"
												:value="item.value"
											></u-radio>
										</u-radio-group>
									</u-form-item>
								</view>
							</template>
						</u-cell>

						<u-cell arrow-direction="down" v-if="formData.isKitchen">
							<template #title>
								<view>
									<u-form-item :borderBottom="false" label-width="80" label="菜品打印:" prop="isPrintRange">
										<u-radio-group style="margin-left: 10rpx" v-model="formData.isPrintRange" @change="onChangeRange">
											<u-radio
												activeColor="#f3c45d"
												:customStyle="{ marginTop: '6px', marginRight: '5px' }"
												v-for="(item, index) in isPrintRangeList"
												:key="index"
												:label="item.name"
												:name="item.value"
												:value="item.value"
											></u-radio>
										</u-radio-group>
									</u-form-item>
								</view>
							</template>
						</u-cell>

						<u-cell isLink :title="`已选择（${formData.foodIds.length}）`" v-if="formData.foodIds.length > 0" @click="getProductList('')"></u-cell>
					</u-cell-group>
				</view>
			</u--form>
		</view>

		<view class="footer-btn" v-if="id">
			<!-- :style="{ width: type ? '100%' : '45%' }" -->
			<!-- <view v-if="!type" class="btn" @click="onAdd">{{ id ? '编辑' : '新增' }}云打印机</view> -->
			<view class="btn" @click="onAdd">保存</view>
		</view>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="show" title="温馨提示" showCancelButton content="确认删除吗？" @cancel="cancel" @confirm="confirm"></u-modal>

		<view style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%)">
			<u-loading-icon size="40" text="表格加载中" :vertical="true" :show="showLoading"></u-loading-icon>
		</view>
		<u-popup :show="productShow" mode="center" @close="onProductClose">
			<ProductTable
				@changeCategory="changeCategory"
				:categoryList="categoryList"
				@checkProduct="checkProduct"
				@search="onSearch"
				:data="tableInfo"
				v-if="popupType === 'table'"
			></ProductTable>
			<view class="preview-box" v-if="popupType === 'Receipt'">
				<view style="font-size: 40rpx; font-weight: 600; margin-top: 30rpx; text-align: center">#07号桌</view>
				<view style="margin-top: 30rpx; line-height: 60rpx; border-bottom: 2rpx dashed #b8b8b8; text-align: center">下单时间：2024-11-25 10：35：10</view>

				<view class="product-info" style="border-bottom: 2rpx dashed #b8b8b8">
					<view class="name">菜品</view>
					<view class="number">数量</view>
					<view class="price">金额</view>
				</view>

				<view class="product-info">
					<view class="name">原味煎饼果子</view>
					<view class="number">1（份）</view>
					<view class="price">15.50</view>
				</view>
				<view class="product-info">
					<view class="name">陕西肉夹馍</view>
					<view class="number">2（份）</view>
					<view class="price">8.00</view>
				</view>
				<view class="product-info" style="margin-bottom: 30rpx; border-bottom: 2rpx dashed #b8b8b8">
					<view class="name">正宗凉皮</view>
					<view class="number">1（份）</view>
					<view class="price">1.00</view>
				</view>

				<view class="df">
					<view>原价</view>
					<view>￥49.00 元</view>
				</view>

				<view class="df">
					<view>优惠</view>
					<view>￥8.00 元</view>
				</view>
				<view class="df">
					<view>应付</view>
					<view>￥41.00 元</view>
				</view>
				<view style="height: 30rpx; border-bottom: 2rpx dashed #b8b8b8"></view>
				<view class="df" style="margin-bottom: 50rpx">
					<view>微信支付</view>
					<view>￥41.00 元</view>
				</view>
			</view>
			<view class="kitchen-preview" v-if="popupType === 'Kitchen'">
				<view style="font-size: 40rpx; font-weight: 600; margin-top: 30rpx; text-align: center">#07号桌</view>
				<view style="margin-top: 30rpx; line-height: 60rpx; border-bottom: 2rpx dashed #b8b8b8; text-align: center">下单时间：2024-11-25 10：35：10</view>
				<view class="df fz" style="padding-top: 30rpx">
					<view>烧鸭</view>
					<view>×1（规格1）</view>
				</view>
				<view style="line-height: 40rpx; margin-bottom: 20rpx">加料：但糖水</view>
				<view class="dashed"></view>
				<view class="df fz" style="padding: 20rpx 0">
					<view>烧鸭</view>
					<view>×1（规格1）</view>
				</view>
				<view class="dashed"></view>

				<view class="fz" style="padding: 30rpx 0">备注:不打包</view>
				<view class="dashed" style="margin-bottom: 100rpx"></view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { scanCode } from '../../../utils/scan';
import ProductTable from '@/pages/workbench/printSetting/components/ProductTable.vue';
import { setArray } from '@/utils/uniUtils.js';
export default {
	name: 'printSetting',
	components: { ProductTable },
	data() {
		return {
			type: 0,
			popupType: '', // 弹框展示
			foodPackPrintTypeList: [
				{ name: '菜品汇总方式', value: 1 },
				{ name: '一菜一单', value: 2 }
			],
			isPrintRangeList: [
				{ name: '全部菜品', value: false },
				{ name: '指定菜品', value: true }
			],
			formData: {
				name: '',
				sn: '',
				key: '',
				isReceipt: true, //开启结账单
				receiptCount: 1, //结账单打印数量
				isKitchen: false, //开启厨打单
				kitchenCount: 0, //厨打单打印数量
				foodPackPrintType: 1, //厨打单 打印方式（1：菜品汇总方式，2：一菜一单）
				isPrintRange: false, //是否设置指定菜品打印
				printSchemeld: 0, // 打印机ID
				foodIds: []
			},
			rules: {
				name: {
					required: true,
					message: '请输入打印机名称',
					trigger: ['blur', 'change'],
					type: 'string'
				},
				sn: {
					required: true,
					message: '请输入序列号',
					trigger: ['blur', 'change'],
					type: 'string'
				},
				key: {
					required: true,
					message: '请输入打印机Key',
					trigger: ['blur', 'change'],
					type: 'string'
				}
			},
			id: null,
			show: false,
			printInfo: {},
			productShow: false,
			tableInfo: {},
			categoryList: [],
			foodCategoryId: null, // 编辑时有传递显示
			searchVal: '', // 编辑时有传递显示
			tempList: [], // 临时选中数据
			showLoading: false
		};
	},
	onLoad({ id }) {
		if (id) {
			// const item = JSON.parse(row);
			this.id = id;
			// this.formData = item;
			// this.printSchemeld = item.id;
			this.getFormDataEdit();
		} else {
			this.id = 0;
		}
	},
	methods: {
		// onTabsClick(e) {
		// 	this.type = e.value;
		// },
		async getFormDataEdit() {
			const res = await this.$api.getPrintDetailAPI({ id: this.id });
			this.formData = res.data;
			this.formData.printSchemeld = res.data.id;
		},
		async onAdd() {
			// 云打印设置
			if (this.formData.foodIds.length < 1 && this.formData.isPrintRange) return this.$refs.uToast.show({ type: 'error', message: '请选择指定菜品' });
			await this.$refs.uForm.validate();
			if (this.id) {
				await this.$api.editPrintInfo(this.formData);
				uni.navigateBack();
			} else {
				await this.$api.addPrintInfo(this.formData);
				uni.navigateBack();
			}
		},
		// 删除
		onDel() {
			this.show = true;
		},
		async confirm() {
			await this.$api.delPrintInfo({ id: this.id });
			this.show = false;
			await this.$refs.uToast.show({ type: 'success', message: '解绑成功' });
			uni.navigateBack();
		},
		cancel() {
			this.show = false;
		},
		// 测试打印单
		async printTest() {
			await this.$api.testPrint({ sn: this.formData.sn });
			this.$refs.uToast.show({ type: 'success', message: '打印成功' });
		},
		// 扫码绑定
		async onScanCode() {
			const res = await scanCode();
			if (res.result) {
				const arr = res.result.split(',');
				if (arr.length > 2) {
					this.formData.sn = res.result.split(',')[0];
					this.formData.key = res.result.split(',')[1];
				} else {
					uni.showToast({
						title: '请扫描正确的二维码',
						icon: 'none',
						duration: 6000
					});
				}
			}
		},
		onChangeRange(e) {
			if (e) {
				// 选择菜品
				this.getProductList('');
			} else {
				this.formData.foodIds = [];
			}
		},
		openPopup(type) {
			// 打开弹窗
			this.productShow = true;
			this.popupType = type;
			if (type === 'table') {
				this.checkFlag();
			}
		},
		onProductClose() {
			this.productShow = false;
			this.tempList = [];
			this.searchVal = '';
			this.foodCategoryId = 1;
		},
		// 获取菜品列表
		async getProductList(name, categoryId) {
			this.showLoading = true;
			if (!categoryId) {
				const result = await this.$api.GetFoodCategory({ pageSize: 999, pageNum: 1 });
				this.categoryList = result.data.list;
				this.categoryList.unshift({ name: '全部', id: 1 });
			}

			const res = await this.$api.getProductListAPI({
				pageSize: 999,
				pageNum: 1,
				name,
				isFoodList: 1,
				foodCategoryId: categoryId ? categoryId : this.categoryList[0].id
			});
			this.tableInfo = res.data;
			if (name || categoryId) {
				this.checkFlag(this.tempList);
			} else {
				this.checkFlag();
			}
			this.openPopup('table');
		},

		checkFlag(temp) {
			if (temp) {
				if (this.formData.foodIds.length > 0) this.tempList.push(...this.formData.foodIds.map((v) => ({ id: v })));
				this.tempList.forEach((v) => {
					this.tableInfo.list.forEach((k) => {
						if (v.id === k.id) {
							this.$set(k, 'checked', true);
						}
					});
				});
				this.showLoading = false;
				return;
			}
			this.formData.foodIds.length > 0
				? this.formData.foodIds.forEach((v) => {
						this.tableInfo.list.forEach((k) => {
							if (v === k.id) {
								this.$set(k, 'checked', true);
								// k.checked = true;
							}
						});
				  })
				: '';
			this.showLoading = false;
		},

		onSearch(e) {
			this.getProductList(e, this.foodCategoryId);
			this.searchVal = e;
		},
		changeCategory(e) {
			// 如果传递过来有选中数据，存起来，关闭弹框时清空，并复制给foodIdS,关闭弹窗时将CategoryId归0
			this.getProductList(this.searchVal, e.id);
			this.foodCategoryId = e.id;
			if (e.arr.length > 0) {
				setArray(this.tempList, e.arr);
			}
		},
		// 选中菜品
		checkProduct(e) {
			console.log(e);
			console.log(this.tempList);
			this.formData.foodIds = [];
			if (e.length > 0) {
				e.forEach((v) => {
					if (v.checked) {
						this.formData.foodIds.push(v.id);
					} else {
						this.formData.foodIds.forEach((k, index) => {
							if (k === v.id) {
								this.formData.foodIds.splice(index, 1);
							}
						});
						this.tempList.forEach((k, index) => {
							if (k.id === v.id) {
								this.tempList.splice(index, 1);
							}
						});
					}
				});
			}
			if (this.tempList.length > 0) {
				const idSet = new Set(this.formData.foodIds); // 提取 array1 中的 id 到 Set
				this.tempList.forEach((item) => {
					if (!idSet.has(item.id)) {
						this.formData.foodIds.push(item.id);
						idSet.add(item.id); // 将新添加的 id 加入 Set 中
					}
				});

				this.formData.foodIds = this.formData.foodIds.map((v) => v);
			}
			this.onProductClose();
		},
		// 绑定打印机
		async onBinding() {
			// 云打印设置
			await this.$refs.uForm.validate();
			const { data } = await this.$api.addPrintInfo({
				name: this.formData.name,
				sn: this.formData.sn,
				key: this.formData.key
			});
			this.id = data;
			this.formData.printSchemeld = data;
			this.formData.id = data;
		},
		onSwitch(type) {
			if (type === 'Receipt') {
				if (this.formData.isReceipt) {
					this.formData.receiptCount = 1;
				} else {
					this.formData.receiptCount = 0;
				}
			} else {
				this.formData.foodPackPrintType = 1; //厨打单 打印方式（1：菜品汇总方式，2：一菜一单）
				this.formData.isPrintRange = false; //是否设置指定菜品打印
				this.formData.foodIds = [];

				this.formData.isKitchen
					? (this.formData.kitchenCount = 1) //厨打单打印数量
					: (this.formData.kitchenCount = 2); //厨打单打印数量
			}
		}
	}
};
</script>

<style scoped lang="scss">
.print-setting-box {
	// background-color: #fff;
	min-height: 100vh;
	padding-bottom: 130rpx;
	.set-print {
		.top {
			padding: 0 20rpx 7rpx;
			background-color: #fff;
			display: flex;
			height: 70rpx;
			align-items: flex-end;
			border-bottom: 1px dashed #b8b8b8;
			.name {
				margin-left: 10rpx;
				font-size: 30rpx;
			}
			.scan {
				flex: 1;
				text-align: end;
				color: #f3c45d;
			}
			.print-pager {
				width: 160rpx;
				line-height: 50rpx;
				text-align: center;
				background-color: #f3c45d;
				color: #f3f4f6;
				font-size: 26rpx;
				margin-right: 20rpx;
			}
		}
		.content {
			background: #fff;
			border-radius: 20rpx;
			margin-top: 20rpx;
			width: 95%;
			margin: 20rpx auto;
			padding: 20rpx 30rpx 40rpx;
		}
		// 小票配置
		.receipt-info {
			margin: 20rpx auto;
			width: 95%;
			background-color: #fff;
			// height: 500rpx;
			border-radius: 20rpx;
		}
	}

	.show-style {
		padding-bottom: 120rpx;
		.content {
			padding: 20rpx;
			.hr {
				margin: 20rpx auto;
				width: 95%;
				height: 2rpx;
				background-color: #f3f3f3;
			}
			.bottom {
				.title {
					padding-top: 30rpx;
					font-size: 34rpx;
					font-weight: 600;
				}
				.preview {
					// height: 600rpx;
					margin-top: 20rpx;
				}
			}
		}
	}

	.footer-btn {
		position: fixed;
		bottom: 0%;
		left: 0%;
		width: 100%;
		height: 120rpx;
		display: flex;
		border-top: 1px solid #f3f4f6;
		align-items: center;
		justify-content: center;
		padding: 20rpx 50rpx;
		background-color: #fff;
		.btn {
			width: 45%;
			height: 100rpx;
			border-radius: 50rpx;
			background-color: #f3c45d;
			color: #fff;
			line-height: 100rpx;
			font-size: 30rpx;
			text-align: center;
		}
	}
}
.df {
	margin-top: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.fz {
	font-size: 34rpx;
}
.dashed {
	border-bottom: 1px dashed #b8b8b8;
	height: 2rpx;
}

.preview-box {
	// height: 840rpx;
	border: 2rpx solid #ccc;
	font-size: 24rpx;
	padding: 0 20rpx;
	padding-top: 30rpx;
	width: 550rpx;
	.product-info {
		display: flex;
		align-items: center;
		line-height: 80rpx;
		.name {
			flex: 1;
		}
		.number {
			width: 120rpx;
			text-align: center;
		}
		.price {
			width: 120rpx;
			text-align: center;
		}
	}
}

.kitchen-preview {
	border: 2rpx solid #ccc;
	font-size: 24rpx;
	padding: 0 30rpx;
	padding-top: 30rpx;
}
</style>
